# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2025/3/8
desc: 
sample: 
"""
import csv
import logging
import os
import random
import time

import gevent
from locust import HttpUser, task, FastHttpUser

from locust import HttpUser, task, constant, FastHttpUser, events
from locust.runners import WorkerRunner, STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP

from loucsttest.dingtalk_email_reminder import send_dingtalk_message
from loucsttest.email_sender import EmailSender
from utils import get_files_path

is_quitting = False

#创建一个list
user_list = []
#遍历user_list


# 指标不满足自动停止
def sendEmail(title, msg):
    email_sender = EmailSender('smtp.163.com', 25, 'testfan2@163.com', 'MSQOTDVQPMKSRZZS')
    email_sender.send_email('279313259@qq.com', title, msg)


def sendDingDing(msg):
    send_dingtalk_message('1111',msg)

is_quitting=False
def checker(environment, **kw):
    global is_quitting
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        print("checker-----")
        time.sleep(1)  # 需要等待系统启动注册
        if environment.runner.stats.total.fail_ratio > 0.01:
            logging.error("Test failed due to failure ratio > 1%")
            is_quitting = True
        elif environment.stats.total.avg_response_time > 200:
            logging.error(f"Test failed due to average response time ratio > 200ms,quitting")
            is_quitting = True
        elif environment.stats.total.get_response_time_percentile(0.95) > 300:
            logging.error(f"Test failed due to 95th percentile response time > 300, quitting")
            is_quitting = True

        if is_quitting:
            error_msg = {}
            error_msg['错误率'] = environment.runner.stats.total.fail_ratio
            error_msg['平均响应时间'] = str(int(environment.stats.total.avg_response_time)) + "ms"
            error_msg['top95'] = str(int(environment.stats.total.get_response_time_percentile(95))) + "ms"
            print(error_msg)
            sendEmail(title='登陆压测指标不满足需求', msg="当前指标：" + error_msg.__str__())
            sendDingDing(msg="当前指标：" + error_msg.__str__())
            environment.runner.quit()
            return


@events.init.add_listener
def on_locust_init(environment, runner, **_kwargs):
    if not isinstance(environment.runner, WorkerRunner):
        gevent.spawn(checker, environment)
def readuser():
    data = []
    with open(file=get_files_path('case.csv'),encoding='utf-8') as f:
        csvreader = csv.reader(f)
        next(csvreader)
        for row in csvreader:
            data.append(row)
    print(data)
    return data

#FastHttpUser 协程库
#HttpUser 普通库
class UserLogin(FastHttpUser):
    host = "http://121.11.97.201:9088"
    data_list =readuser()

    @task
    def login(self):
        #self.client 包装了requests
        random_row = random.choice(self.data_list)
        data = {
            'userName': random_row[0],
            'password': random_row[1]
        }
        with self.client.post(url='/pinter/bank/api/login',
                         data=data,catch_response=True) as reponse:
            if reponse.json()['code'] == '0':
                reponse.success()
            else:
                reponse.failure(reponse.json())

if __name__ == '__main__':
    os.system('locust -f Login.py')
    #readuser() #list list





